<template>
  <!-- 预警级别设置 -->
  <div>
    <div class="detail-header">
      {{projectDetail.name}}
    </div>
    <div style="height: 85vh;overflow: auto">
      <div v-if="showUserSelect">
        <div class="phone-class">
          <span class="phone-title">预警通知人员</span>
        </div>
        <div style="padding: 0px 40px" class="sms_view">
          <el-button icon="el-icon-plus" :disabled="!hasPermission('project:warning:rules')" @click.stop="handleAdd" type="primary" size="small" class="phone-btn">添加通知人
          </el-button>
          <el-button style="margin-bottom: 20px" :disabled="!hasPermission('project:warning:rules')" @click="submitPhoneData()" size="small" icon="el-icon-folder-checked"
                     type="success" class="phone-btn">保存
          </el-button>
          <p style="color: red;margin-bottom: 10px">说明：触发预警后，监测单位自动推送；业主单位需在《监控测量-预警消息管理》页面手动推送！</p>
          <el-table :data="userList" style="margin-bottom: 20px;" height="70vh">
            <el-table-column label="序号" fixed width="70" align="center">
              <template slot-scope="scope">
                {{scope.$index + 1}}
              </template>
            </el-table-column>
            <el-table-column prop="userType" label="用户类型" width="200">
              <template slot-scope="scope">
                <el-radio-group v-model="scope.row.userType" size="mini" >
                  <el-radio-button :label=4>监测单位</el-radio-button>
                  <el-radio-button :label=5>业主单位</el-radio-button>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column prop="pushType" label="推送方式" width="250">
              <template slot-scope="scope">
                <el-radio-group v-model="scope.row.type" size="mini" @change="changeType(scope.$index,scope.row.type)">
                  <el-radio-button :label=1>短信</el-radio-button>
                  <el-radio-button :label=2>公众号</el-radio-button>
                  <el-radio-button :label=3>手动录入</el-radio-button>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column prop="messageModel" label="短信模板" width="200">
              <template slot-scope="scope">
                <el-select v-model="scope.row.messageModel" :disabled="scope.row.type===2" size="mini" clearable
                           placeholder="选择短信模板">
                  <el-option
                    v-for="item in EnumMessageSecretList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="user" label="通知账号" min-width="150">
              <template slot-scope="scope">
                <el-select v-model="scope.row.id" :disabled="scope.row.type===3" size="mini" clearable
                           placeholder="选择通知人" @change="changeUser(scope.$index,scope.row.id)">
                  <el-option
                    v-for="item in userSelectList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    :disabled="!item.phone && scope.row.type===1">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="通知号码" min-width="180">
              <template slot-scope="scope">
                <el-input v-model="scope.row.phone" :disabled="scope.row.type!==3" show-word-limit maxlength="11"
                          clearable placeholder="手机号"
                          oninput="this.value = this.value.replace(/[^0-9]/g, '');"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="pushType" label="降雨预警推送" width="120">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.rainFlag"
                  active-color="#13ce66"
                  :inactive-value=0
                  :active-value=1
                  inactive-color="#6a6a6a">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="120">
              <template slot-scope="scope">
                <el-input type="text" v-model="scope.row.remark" placeholder="备注"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="user" label="预警等级>=时发送通知" min-width="180">
              <template slot-scope="scope">
                <el-select v-model="scope.row.level" size="mini" clearable placeholder="选择预警等级">
                  <el-option
                    v-for="item in EnumWarningLevelList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                    :disabled="item.code === 1">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  :disabled="!hasPermission('project:warning:rules')"
                  @click="userDelete(scope.$index)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div v-else style="margin-top: 15%"></div>

    </div>
  </div>
</template>

<script>
  import {
    warningRuleList,
    warningRuleUpdate,
    warningUserUpdate,
    queryUserByProject,
    queryUserList,
    warningRuleFlag
  } from '@/services/model/sensor'
  import Format from '@/utils/format'
  import Enums from '@/utils/enums'
  import Permission from '@/utils/permission'
  import {store} from "../work-point.store";

  export default {
    mixins: [Enums],
    data() {
      return {
        activeName: '倾角仪',
        form: {
          workPointId: ''
        },
        total: 0,
        tableList: [],
        updateForm: {},
        phoneInfo: {
          userIdList: [],
          workPointId: ''
        },
        flag: false,
        warningRules: [],
        isShowDialog: false,
        warningTitle: '',
        userSelectList: [],
        userList: [],
        EnumWarningLevelList: [],
        showUserSelect: false,
        EnumMessageSecretList: []
      }
    },
    filters: {

      // 时间格式化
      formatTimer(timer) {
        return Format(new Date(timer))
      },
      // 修改表头
      threTitle(monitorType) {
        switch (monitorType) {
          case 8 :
            return '倾角(θ ≥ Degree)'// 倾角
          case 6 :
            return '应力(F < % * 初始值)'// 应力
          case 4 :
            return '降雨量（>=mm/h)'
          default:
            return '位移(X ≥ Ymm)'
        }
      }
    },
    computed: {
      projectDetail() {
        return store.projectInfo
      },
    },
    methods: {
      // 判断权限
      hasPermission(permissionStr) {
        return Permission(this.$store.state.userInfo, permissionStr)
      },
      changeType(index, type) {
        if (type === 3) {
          //选择手动录入清空已选的用户id
          this.userList[index].id = ''
        }
      },
      changeUser(index, userId) {
        let ts = this.userSelectList.filter(x => x.id === userId)[0];
        this.userList[index].phone = ts.phone
      },
      async changeFlag() {
        this.updateForm.flag = this.flag ? 1 : 0
        let res = await warningRuleFlag(this.updateForm)
      },
      handleAdd() {
        this.userList.push({
          id: '',
          phone: '',
          type: 1,
        })
      },
      // 获取当前的序号
      getIndex(index) {
        let param = index + 1
        return param
      },
      //查询已关联的通知人信息
      async queryUserList(projectId) {
        let res = await queryUserList({projectId: projectId})
        this.userList = res.data
      },
      //查询通知人选择列表
      async queryUserSelectList(projectId) {
        let res = await queryUserByProject({projectId: projectId});
        this.userSelectList = res.data;
      },
      // 预警列表
      async queryList(workPointId) {
        this.showUserSelect = false
        const projectId = this.$route.params?.projectId
        //项目级别控制，查询可选用户
        if (!workPointId && projectId) {
          this.showUserSelect = true
          this.queryUserSelectList(projectId)
          this.queryUserList(projectId)
        }
        this.form.workPointId = workPointId
        this.form.projectId = projectId
        let res = await warningRuleList(this.form)
        this.warningRules = res.data || []
        this.phoneInfo.userIdList = this.warningRules[0].userIdList || []
        this.flag = this.warningRules[0].flag === 1 ? true : false;
        this.updateForm.workPointId = workPointId;
        this.total = Number(res.data?.total)
      },
      // 删除某个通知人
      userDelete(index) {
        this.userList.splice(index, 1)
        this.phoneInfo.userIdList.splice(index, 1)
      },
      // 修改
      updateWarning(item) {
        this.updateForm = item
        this.updateForm.workPointId = this.form.workPointId
        this.submitData()
      },
      // 修改
      async submitData() {
        let res = await warningRuleUpdate(this.updateForm)
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '修改成功'
          })
          this.queryList(this.form.workPointId)
          return true
        }
      },
      // 确定修改phone
      async submitPhoneData() {
        this.phoneInfo.projectId = this.form.projectId
        this.phoneInfo.userIdList = this.userList

        let res = await warningUserUpdate(this.phoneInfo)
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '修改成功'
          })
          this.queryList(this.form.workPointId)
          return true
        }
      },
    },
    activated() {
      this.queryList()
    },
    mounted() {
      this.queryDictList(['EnumWarningLevel','EnumMessageSecret'], ['EnumWarningLevelList','EnumMessageSecretList'])
    },
  }
</script>
<style scoped="scoped" lang="less">
  .page {
    .detail-header {
      color: #1990FE;
    }

  }

  .s-phone {
    width: 150px;
  }

  .warning-header {
    margin-bottom: 10px;
    color: #606266;
    height: 30px;
    line-height: 30px;
  }

  .warning-header h2 {
    font-size: 16px;
    font-weight: bold;
  }

  .s-green {
    color: #2dca7f;
  }

  .s-red {
    color: #f35e5f;
  }

  /deep/ .el-table__header .el-table-column--selection .cell .el-checkbox:after {
    content: " 是否预警";
    color: #909399;
    font-size: 13px;
  }

  .phone-class {
    margin: 10px 0 10px 40px;
    border-bottom: 2px solid #1990FE !important;

    span {
      color: white
    }

    .phone-btn {
      background: #1990FE;
      width: 80px;
      text-align: center;
      border-color: transparent
      // height: 20px
      // color
    }
  ;
  }

  .phone-class .phone-title {
    color: #1990FE;

    font-size: 18px;
    font-weight: 600;
  }

  .phone-class .phone-info {
    color: rgb(81, 85, 99);
    font-size: 15px;
    margin-left: 5px;
  }

  .addNotifier {
    // background-color: red !important;
  }

  .sms_view {
    /deep/ .el-table td, .el-table th {
      padding: 4px 0;
      font-size: 13px;
    }
  }
</style>
